package com.william.jdbcplus.boot.test.service.impl;

import com.william.jdbcplus.boot.starter.util.DaoUtil;
import com.william.jdbcplus.boot.test.entity.SysDemo;
import com.william.jdbcplus.boot.test.enums.TimeUnitEnum;
import com.william.jdbcplus.boot.test.service.SysDemoService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class SysDemoServiceImpl implements SysDemoService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void testTransactional(List<String> ids) throws Exception {
        List<SysDemo> demoList = DaoUtil.BASE.listAll(SysDemo.class);

        List<String> idList = demoList.stream().map(k -> k.getId().toString()).collect(Collectors.toList());
        DaoUtil.BASE.realDelByIds(idList, SysDemo.class);

        if (false) {
            throw new Exception("添加新的广告位资源失败，回滚");
        }

        DaoUtil.BASE.addList(demoList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void txInsertBatch() {
        List<SysDemo> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            SysDemo entity = new SysDemo();
            entity.setCode("456" + i);
            entity.setName("小明" + i);
            entity.setTimeUnit(TimeUnitEnum.SECOND);
            list.add(entity);
        }

        DaoUtil.BASE.addList(list);

        SysDemo entity = new SysDemo();
        entity.setCode("456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456456");
        entity.setName("小明");
        entity.setTimeUnit(TimeUnitEnum.SECOND);
        DaoUtil.BASE.add(entity);
    }

    @Override
    public Integer testCount() {
        return DaoUtil.BASE.countAll(SysDemo.class);
    }
}
